//
//  PageContentView.swift
//  SwiftDemo
//
//  Created by liguoqing on 2022/6/26.
//  Copyright © 2022 guoqing.li. All rights reserved.
//

import UIKit

private let kCollectCellID = "collectionCellID"

protocol PageContentViewDelegate : AnyObject {
    func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int)
}

class PageContentView: UIView {
    // MARK - 定义属性
    private var childVcs : [UIViewController]
    private weak var parentVC : UIViewController?
    private var startOffsetX : CGFloat = 0
    // 是否禁用collectionView代理
    private var isForbidScollViewDelegate : Bool = false
    
    weak var delegate: PageContentViewDelegate?
    
    fileprivate lazy var collectionView: UICollectionView = {[weak self] in
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = (self?.bounds.size)!
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.scrollDirection = .horizontal
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout);
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        collectionView.bounces = false
        collectionView.isPagingEnabled = true;
        collectionView.delegate = self;
        collectionView.dataSource = self;
        collectionView .register(UICollectionViewCell.self, forCellWithReuseIdentifier: kCollectCellID)
        return collectionView
    }()
    
    // MARK - 自定义构造方法
    init(frame: CGRect, childVcs: [UIViewController], parentVC: UIViewController?) {
        self.childVcs = childVcs;
        self.parentVC = parentVC;
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension PageContentView {
    private func setupUI(){
       addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.edges.equalTo(0)
        }
    }
}

extension PageContentView : UICollectionViewDataSource
{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return childVcs.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCollectCellID, for: indexPath)
        for view in cell.contentView.subviews {
            view.removeFromSuperview()
        }
        let childVC:UIViewController = childVcs[indexPath.item]
        childVC.view.frame = cell.contentView.bounds
        cell.contentView.addSubview(childVC.view)
        return cell
    }
}

extension PageContentView : UICollectionViewDelegate {
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        
        isForbidScollViewDelegate = false;
        
        startOffsetX = scrollView.contentOffset.x
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        // 判断是否标题 点击事件
        if isForbidScollViewDelegate {return}
        // 定义需要的数据
        var progress : CGFloat = 0.0
        var sourceIndex : Int = 0
        var targetIndex : Int = 0
        // 判断滑动方向
        let currentOffsetX = scrollView.contentOffset.x
        let scrollViewW = scrollView.frame.width
        if currentOffsetX > startOffsetX { // 左滑
            //2.1 计算 progress
            progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)
            
            //2.2 计算 sourceIndex
            sourceIndex = Int(currentOffsetX / scrollViewW)
            
            //2.3 计算 targetIndex
            targetIndex = sourceIndex + 1
            if targetIndex >= childVcs.count {
                targetIndex = childVcs.count - 1
            }
            
            //2.4 如果完全滑过去
            if currentOffsetX - startOffsetX == scrollViewW {
                progress = 1
                targetIndex = sourceIndex
            }
        }else{
            //2.1 计算 progress
            progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW))
            
            //2.2 计算 targetIndex
            targetIndex = Int(currentOffsetX / scrollViewW)
            
            //2.3 计算 sourceIndex
            sourceIndex = targetIndex + 1
            if sourceIndex >= childVcs.count {
                sourceIndex = childVcs.count - 1
            }
        }
        //3. 将 progress/sourceIndex/targetIndex 传递给 titleView
        delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
    }
}

extension PageContentView {
    func setContentIndex (currentIndex : Int) {
        // 1.记录需要禁止进行代理方法
        isForbidScollViewDelegate = true
        // 2.滚动到正确位置
        let offsetX = CGFloat(currentIndex) * collectionView.bounds.width;
        collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false)
        
    }
}


